package com.pethospital.servlet;

import com.pethospital.entity.PageResult;
import com.pethospital.entity.Pet;
import com.pethospital.entity.User;
import com.pethospital.service.PetService;
import com.pethospital.service.impl.PetServiceImpl;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * 宠物控制器
 * Pet Controller Servlet
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class PetServlet extends HttpServlet {
    
    private PetService petService = new PetServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 从URL路径获取操作类型
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "";

        // 如果路径中没有操作，尝试从参数中获取
        if (action.isEmpty()) {
            action = request.getParameter("action");
            if (action == null) {
                action = "";
            }
        }
        
        try {
            switch (action) {
                case "list":
                    handleList(request, response);
                    break;
                case "my-pets":
                    handleMyPets(request, response);
                    break;
                case "add":
                    handleAdd(request, response);
                    break;
                case "edit":
                    handleEdit(request, response);
                    break;
                case "update":
                    handleUpdate(request, response);
                    break;
                case "delete":
                    handleDelete(request, response);
                    break;
                case "batchDelete":
                    handleBatchDelete(request, response);
                    break;
                case "updateStatus":
                    handleUpdateStatus(request, response);
                    break;
                case "view":
                    handleView(request, response);
                    break;
                case "getBreeds":
                    handleGetBreeds(request, response);
                    break;
                case "statistics":
                    handleStatistics(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的操作");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "服务器内部错误");
        }
    }
    
    /**
     * 处理宠物列表查询（管理员）
     */
    private void handleList(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        // 检查管理员权限
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 获取查询参数
        String petName = request.getParameter("petName");
        String petType = request.getParameter("petType");
        String breed = request.getParameter("breed");
        String status = request.getParameter("status");

        // 获取排序参数
        String sortField = request.getParameter("sortField");
        String sortOrder = request.getParameter("sortOrder");

        // 设置默认排序
        if (sortField == null || sortField.trim().isEmpty()) {
            sortField = "createTime";
        }
        if (sortOrder == null || sortOrder.trim().isEmpty()) {
            sortOrder = "desc";
        }

        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        try {
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            String sizeStr = request.getParameter("size");
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                pageSize = Integer.parseInt(sizeStr);
            }
        } catch (NumberFormatException e) {
            // 使用默认值
        }
        
        // 查询宠物列表
        PageResult<Pet> pageResult = petService.searchPetsWithSort(petName, petType, breed, status, null,
                                                                  sortField, sortOrder, currentPage, pageSize);

        // 设置请求属性
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("petName", petName);
        request.setAttribute("petType", petType);
        request.setAttribute("breed", breed);
        request.setAttribute("status", status);
        request.setAttribute("sortField", sortField);
        request.setAttribute("sortOrder", sortOrder);
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("petTypes", petService.getAllPetTypes());
        
        // 转发到宠物列表页面
        request.getRequestDispatcher("/pages/admin/pet-list.jsp").forward(request, response);
    }
    
    /**
     * 处理我的宠物查询（普通用户）
     */
    private void handleMyPets(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }
        
        // 获取查询参数
        String petName = request.getParameter("petName");
        String petType = request.getParameter("petType");
        String status = request.getParameter("status");
        
        // 获取分页参数
        int currentPage = 1;
        int pageSize = 10;
        
        try {
            String pageStr = request.getParameter("page");
            if (pageStr != null && !pageStr.trim().isEmpty()) {
                currentPage = Integer.parseInt(pageStr);
            }
            
            String sizeStr = request.getParameter("size");
            if (sizeStr != null && !sizeStr.trim().isEmpty()) {
                pageSize = Integer.parseInt(sizeStr);
            }
        } catch (NumberFormatException e) {
            // 使用默认值
        }
        
        // 查询用户的宠物列表
        PageResult<Pet> pageResult = petService.searchPets(petName, petType, null, status, 
                                                          currentUser.getUserId(), currentPage, pageSize);
        
        // 设置请求属性
        request.setAttribute("pageResult", pageResult);
        request.setAttribute("petName", petName);
        request.setAttribute("petType", petType);
        request.setAttribute("status", status);
        request.setAttribute("petTypes", petService.getAllPetTypes());
        
        // 转发到我的宠物页面
        request.getRequestDispatcher("/pages/user/my-pets.jsp").forward(request, response);
    }
    
    /**
     * 处理添加宠物
     */
    private void handleAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        // GET请求：显示添加页面
        if ("GET".equalsIgnoreCase(request.getMethod())) {
            request.setAttribute("petTypes", petService.getAllPetTypes());
            String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                "/pages/admin/pet-add.jsp" : "/pages/user/pet-add.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);
            return;
        }

        // POST请求：处理添加操作
        String petName = request.getParameter("petName");
        String petType = request.getParameter("petType");
        String breed = request.getParameter("breed");
        String gender = request.getParameter("gender");
        String ageStr = request.getParameter("age");
        String weightStr = request.getParameter("weight");
        String color = request.getParameter("color");
        String description = request.getParameter("description");
        String status = request.getParameter("status");
        String ownerIdStr = request.getParameter("ownerId");
        
        // 创建宠物对象
        Pet pet = new Pet();
        pet.setPetName(petName);
        pet.setPetType(petType);
        pet.setBreed(breed);
        pet.setGender(gender);
        pet.setColor(color);
        pet.setDescription(description);
        pet.setStatus(status != null ? status : "healthy");
        
        // 设置年龄
        if (ageStr != null && !ageStr.trim().isEmpty()) {
            try {
                pet.setAge(Integer.parseInt(ageStr));
            } catch (NumberFormatException e) {
                // 忽略无效的年龄
            }
        }
        
        // 设置体重
        if (weightStr != null && !weightStr.trim().isEmpty()) {
            try {
                pet.setWeight(new BigDecimal(weightStr));
            } catch (NumberFormatException e) {
                // 忽略无效的体重
            }
        }
        
        // 设置主人ID
        if ("admin".equals(currentUser.getUserType()) && ownerIdStr != null && !ownerIdStr.trim().isEmpty()) {
            try {
                pet.setOwnerId(Integer.parseInt(ownerIdStr));
            } catch (NumberFormatException e) {
                pet.setOwnerId(currentUser.getUserId());
            }
        } else {
            pet.setOwnerId(currentUser.getUserId());
        }
        
        // 添加宠物
        if (petService.addPet(pet)) {
            try {
                String successMsg = URLEncoder.encode("添加成功", "UTF-8");
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/pet/list?success=" + successMsg : "/pet/my-pets?success=" + successMsg;
                response.sendRedirect(request.getContextPath() + redirectUrl);
            } catch (Exception e) {
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/pet/list" : "/pet/my-pets";
                response.sendRedirect(request.getContextPath() + redirectUrl);
            }
        } else {
            request.setAttribute("error", "添加失败");
            request.setAttribute("pet", pet);
            request.setAttribute("petTypes", petService.getAllPetTypes());
            
            String forwardUrl = "admin".equals(currentUser.getUserType()) ? 
                "/pages/admin/pet-add.jsp" : "/pages/user/pet-add.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);
        }
    }
    
    /**
     * 处理编辑宠物页面
     */
    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }
        
        String petIdStr = request.getParameter("id");
        if (petIdStr == null || petIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID不能为空");
            return;
        }
        
        try {
            Integer petId = Integer.parseInt(petIdStr);
            Pet pet = petService.getPetById(petId);
            
            if (pet == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "宠物不存在");
                return;
            }
            
            // 检查权限
            if (!petService.hasPermission(petId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }
            
            request.setAttribute("pet", pet);
            request.setAttribute("petTypes", petService.getAllPetTypes());
            request.setAttribute("breeds", petService.getBreedsByType(pet.getPetType()));
            
            String forwardUrl = "admin".equals(currentUser.getUserType()) ? 
                "/pages/admin/pet-edit.jsp" : "/pages/user/pet-edit.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);
            
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID格式错误");
        }
    }

    /**
     * 处理更新宠物
     */
    private void handleUpdate(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        // 检查是否为multipart请求
        if (!ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "请求格式错误");
            return;
        }

        try {
            // 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(5 * 1024 * 1024); // 5MB
            upload.setSizeMax(5 * 1024 * 1024);

            List<FileItem> items = upload.parseRequest(request);

            String petIdStr = null;
            String petName = null;
            String petType = null;
            String breed = null;
            String gender = null;
            String ageStr = null;
            String weightStr = null;
            String color = null;
            String description = null;
            String status = null;
            FileItem photoFile = null;

            // 解析表单字段
            for (FileItem item : items) {
                if (item.isFormField()) {
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");

                    switch (fieldName) {
                        case "petId":
                            petIdStr = fieldValue;
                            break;
                        case "petName":
                            petName = fieldValue;
                            break;
                        case "petType":
                            petType = fieldValue;
                            break;
                        case "breed":
                            breed = fieldValue;
                            break;
                        case "gender":
                            gender = fieldValue;
                            break;
                        case "age":
                            ageStr = fieldValue;
                            break;
                        case "weight":
                            weightStr = fieldValue;
                            break;
                        case "color":
                            color = fieldValue;
                            break;
                        case "description":
                            description = fieldValue;
                            break;
                        case "status":
                            status = fieldValue;
                            break;
                    }
                } else if ("photo".equals(item.getFieldName()) && item.getSize() > 0) {
                    photoFile = item;
                }
            }

            System.out.println("更新宠物 - petIdStr: " + petIdStr);

            if (petIdStr == null || petIdStr.trim().isEmpty()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID不能为空");
                return;
            }

            Integer petId = Integer.parseInt(petIdStr);

            // 检查权限
            if (!petService.hasPermission(petId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            // 获取原宠物信息
            Pet pet = petService.getPetById(petId);
            if (pet == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "宠物不存在");
                return;
            }

            // 更新宠物信息
            pet.setPetName(petName);
            pet.setPetType(petType);
            pet.setBreed(breed);
            pet.setGender(gender);
            pet.setColor(color);
            pet.setDescription(description);
            pet.setStatus(status);

            // 设置年龄
            if (ageStr != null && !ageStr.trim().isEmpty()) {
                try {
                    pet.setAge(Integer.parseInt(ageStr));
                } catch (NumberFormatException e) {
                    pet.setAge(null);
                }
            } else {
                pet.setAge(null);
            }

            // 设置体重
            if (weightStr != null && !weightStr.trim().isEmpty()) {
                try {
                    pet.setWeight(new BigDecimal(weightStr));
                } catch (NumberFormatException e) {
                    pet.setWeight(null);
                }
            } else {
                pet.setWeight(null);
            }

            // 处理图片上传
            if (photoFile != null && photoFile.getSize() > 0) {
                try {
                    // 验证文件类型
                    String fileName = photoFile.getName();
                    String contentType = photoFile.getContentType();
                    if (contentType == null || (!contentType.startsWith("image/"))) {
                        request.setAttribute("error", "只能上传图片文件");
                        request.setAttribute("pet", pet);
                        request.setAttribute("petTypes", petService.getAllPetTypes());
                        request.setAttribute("breeds", petService.getBreedsByType(pet.getPetType()));

                        String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                            "/pages/admin/pet-edit.jsp" : "/pages/user/pet-edit.jsp";
                        request.getRequestDispatcher(forwardUrl).forward(request, response);
                        return;
                    }

                    // 生成文件名
                    String fileExtension = "";
                    if (fileName != null && fileName.contains(".")) {
                        fileExtension = fileName.substring(fileName.lastIndexOf("."));
                    } else if (contentType.contains("jpeg") || contentType.contains("jpg")) {
                        fileExtension = ".jpg";
                    } else if (contentType.contains("png")) {
                        fileExtension = ".png";
                    } else if (contentType.contains("gif")) {
                        fileExtension = ".gif";
                    } else {
                        fileExtension = ".jpg"; // 默认
                    }

                    String newFileName = "pet_" + pet.getPetId() + "_" + System.currentTimeMillis() + fileExtension;

                    // 确保上传目录存在
                    String uploadPath = getServletContext().getRealPath("/uploads/pets/");
                    java.io.File uploadDir = new java.io.File(uploadPath);
                    if (!uploadDir.exists()) {
                        uploadDir.mkdirs();
                    }

                    // 保存文件
                    java.io.File savedFile = new java.io.File(uploadPath, newFileName);
                    photoFile.write(savedFile);

                    // 更新宠物照片URL
                    String photoUrl = "/uploads/pets/" + newFileName;
                    pet.setPhotoUrl(photoUrl);

                } catch (Exception e) {
                    e.printStackTrace();
                    request.setAttribute("error", "图片上传失败：" + e.getMessage());
                    request.setAttribute("pet", pet);
                    request.setAttribute("petTypes", petService.getAllPetTypes());
                    request.setAttribute("breeds", petService.getBreedsByType(pet.getPetType()));

                    String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pages/admin/pet-edit.jsp" : "/pages/user/pet-edit.jsp";
                    request.getRequestDispatcher(forwardUrl).forward(request, response);
                    return;
                }
            }

            if (petService.updatePet(pet)) {
                try {
                    String successMsg = URLEncoder.encode("更新成功", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list?success=" + successMsg : "/pet/my-pets?success=" + successMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list" : "/pet/my-pets";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            } else {
                request.setAttribute("error", "更新失败");
                request.setAttribute("pet", pet);
                request.setAttribute("petTypes", petService.getAllPetTypes());
                request.setAttribute("breeds", petService.getBreedsByType(pet.getPetType()));

                String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                    "/pages/admin/pet-edit.jsp" : "/pages/user/pet-edit.jsp";
                request.getRequestDispatcher(forwardUrl).forward(request, response);
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID格式错误");
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "处理请求时发生错误");
        }
    }

    /**
     * 处理删除宠物
     */
    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String petIdStr = request.getParameter("id");
        if (petIdStr == null || petIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID不能为空");
            return;
        }

        try {
            Integer petId = Integer.parseInt(petIdStr);

            // 检查权限
            if (!petService.hasPermission(petId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            if (petService.deletePet(petId)) {
                try {
                    String successMsg = URLEncoder.encode("删除成功", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list?success=" + successMsg : "/pet/my-pets?success=" + successMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list" : "/pet/my-pets";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("删除失败", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list?error=" + errorMsg : "/pet/my-pets?error=" + errorMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list" : "/pet/my-pets";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID格式错误");
        }
    }

    /**
     * 处理批量删除宠物
     */
    private void handleBatchDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String[] petIdStrs = request.getParameterValues("petIds");
        if (petIdStrs == null || petIdStrs.length == 0) {
            try {
                String errorMsg = URLEncoder.encode("请选择要删除的宠物", "UTF-8");
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/pet/list?error=" + errorMsg : "/pet/my-pets?error=" + errorMsg;
                response.sendRedirect(request.getContextPath() + redirectUrl);
            } catch (Exception e) {
                String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                    "/pet/list" : "/pet/my-pets";
                response.sendRedirect(request.getContextPath() + redirectUrl);
            }
            return;
        }

        try {
            Integer[] petIds = new Integer[petIdStrs.length];
            for (int i = 0; i < petIdStrs.length; i++) {
                petIds[i] = Integer.parseInt(petIdStrs[i]);

                // 检查每个宠物的权限
                if (!petService.hasPermission(petIds[i], currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                    response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                    return;
                }
            }

            if (petService.batchDeletePets(petIds)) {
                try {
                    String successMsg = URLEncoder.encode("批量删除成功", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list?success=" + successMsg : "/pet/my-pets?success=" + successMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list" : "/pet/my-pets";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            } else {
                try {
                    String errorMsg = URLEncoder.encode("批量删除失败", "UTF-8");
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list?error=" + errorMsg : "/pet/my-pets?error=" + errorMsg;
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                } catch (Exception e) {
                    String redirectUrl = "admin".equals(currentUser.getUserType()) ?
                        "/pet/list" : "/pet/my-pets";
                    response.sendRedirect(request.getContextPath() + redirectUrl);
                }
            }
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID格式错误");
        }
    }

    /**
     * 处理更新宠物状态
     */
    private void handleUpdateStatus(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.getWriter().write("error");
            return;
        }

        String petIdStr = request.getParameter("id");
        String status = request.getParameter("status");

        if (petIdStr == null || petIdStr.trim().isEmpty() ||
            status == null || status.trim().isEmpty()) {
            response.getWriter().write("error");
            return;
        }

        try {
            Integer petId = Integer.parseInt(petIdStr);

            // 检查权限
            if (!petService.hasPermission(petId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.getWriter().write("unauthorized");
                return;
            }

            if (petService.updatePetStatus(petId, status)) {
                response.getWriter().write("success");
            } else {
                response.getWriter().write("error");
            }
        } catch (NumberFormatException e) {
            response.getWriter().write("error");
        }
    }

    /**
     * 处理查看宠物详情
     */
    private void handleView(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            response.sendRedirect(request.getContextPath() + "/pages/common/login.jsp");
            return;
        }

        String petIdStr = request.getParameter("id");
        if (petIdStr == null || petIdStr.trim().isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID不能为空");
            return;
        }

        try {
            Integer petId = Integer.parseInt(petIdStr);
            Pet pet = petService.getPetById(petId);

            if (pet == null) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "宠物不存在");
                return;
            }

            // 检查权限
            if (!petService.hasPermission(petId, currentUser.getUserId(), "admin".equals(currentUser.getUserType()))) {
                response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
                return;
            }

            request.setAttribute("pet", pet);

            String forwardUrl = "admin".equals(currentUser.getUserType()) ?
                "/pages/admin/pet-view.jsp" : "/pages/user/pet-view.jsp";
            request.getRequestDispatcher(forwardUrl).forward(request, response);

        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "宠物ID格式错误");
        }
    }

    /**
     * 处理获取品种列表
     */
    private void handleGetBreeds(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String petType = request.getParameter("petType");
        if (petType == null || petType.trim().isEmpty()) {
            response.getWriter().write("[]");
            return;
        }

        List<String> breeds = petService.getBreedsByType(petType);

        // 构建JSON响应
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < breeds.size(); i++) {
            json.append("\"").append(breeds.get(i)).append("\"");
            if (i < breeds.size() - 1) {
                json.append(",");
            }
        }
        json.append("]");

        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json.toString());
    }

    /**
     * 处理统计信息
     */
    private void handleStatistics(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }

        // 获取统计数据
        List<Object[]> typeStatistics = petService.getPetTypeStatistics();
        List<Object[]> statusStatistics = petService.getStatusStatistics();
        long totalCount = petService.getTotalPetCount();

        request.setAttribute("typeStatistics", typeStatistics);
        request.setAttribute("statusStatistics", statusStatistics);
        request.setAttribute("totalCount", totalCount);

        request.getRequestDispatcher("/pages/admin/pet-statistics.jsp").forward(request, response);
    }
}
